package com.lzb.yabbs.net;

import com.lzb.yabbs.AppConfig;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;

import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * Created by liuzaibing on 2015/8/30.
 */
public class OkHttpBase {
    private static final OkHttpClient mOK_HTTP_CLIENT=new OkHttpClient();
    public static final int TIMEOUT=20;
    public static final int WRITE_TIMEOUT=20;
    public static final int READ_TIMEOUT=20;

    static {
        mOK_HTTP_CLIENT.setConnectTimeout(TIMEOUT, TimeUnit.SECONDS);
        mOK_HTTP_CLIENT.setWriteTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
        mOK_HTTP_CLIENT.setReadTimeout(READ_TIMEOUT,TimeUnit.SECONDS);
    }

    /**
     * 开启异步线程访问网络
     *
     * @param request
     * @param responseCallback
     */
    public static void enqueue(Request request,Callback responseCallback){
        mOK_HTTP_CLIENT.newCall(request).enqueue(responseCallback);
    }

    /**
     * 格式化参数
     * @param params
     * @return
     */
    public static String formatParams(List<BasicNameValuePair> params){
        return URLEncodedUtils.format(params, AppConfig.UTF8);
    }

    /**
     * 将参数生成get url
     *
     * @param url
     * @param params
     * @return
     */
    public static String attachHttpGetParams(String url,List<BasicNameValuePair> params){
        return url+"?"+formatParams(params);
    }

    /**
     * get数据流
     * @param url
     * @return
     */
    public static InputStream getStream(String url) {
        try {
            return mOK_HTTP_CLIENT.newCall(new Request.Builder().url(url).get().build()).execute().body().byteStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
